﻿using System;
using System.ComponentModel;
using SedionFormDesigner.Designer;
using SedionFormDesigner.Infrastructure;
using System.ComponentModel.Design;

namespace SedionFormDesigner.Infrastructure
{
    /// <summary>
    ///  使所有的组件都有name属性
    /// </summary>
    [ProvideProperty("name", typeof(IComponent))]
    internal class SedionNameExtenderProvider : IExtenderProvider
    {
        private SedionDesignerHost host;

        private static Attribute[] designerNameAttribute = new Attribute[] { new SedionDesignerName(true) };

        public SedionNameExtenderProvider(SedionDesignerHost host)
        {
            this.host = host;
        }

        public SedionDesignerHost Host
        {
            get
            {
                return host;
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SedionDesignerName(true),
        ParenthesizePropertyName(true),
        MergableProperty(false),
        Description("The name property for the component"),
        Category("Design")]
        public virtual String GetName(IComponent comp)
        {
            ISite site = comp.Site;
            if (site != null)
                return site.Name;

            return null;
        }

        public void SetName(IComponent comp, String newName)
        {
            newName = newName.Trim();
            SedionDesignSite site = (SedionDesignSite)comp.Site;

            if (newName.Equals(site.Name)) return;

            if (String.Compare(newName, site.Name, true) != 0)
                Host.CheckName(newName);

            ((IComponentChangeService)Host).OnComponentChanging(comp, TypeDescriptor.GetProperties(comp, designerNameAttribute)["Name"]);

            Host.Sites.Remove(site.Name);
            Host.Sites[newName] = site;

            String oldName = site.Name;
            site.SetName(newName);

            Host.OnComponentRename(new ComponentRenameEventArgs(comp, oldName, newName));
            ((IComponentChangeService)Host).OnComponentChanged(comp, TypeDescriptor.GetProperties(comp, designerNameAttribute)["Name"], oldName, newName);
        }

        #region IExtenderProvider 成员

        public virtual bool CanExtend(object extendee)
        {
            if (extendee == host.RootComponent)
                return false;
            if (!TypeDescriptor.GetAttributes(extendee)[typeof(InheritanceAttribute)].Equals(InheritanceAttribute.NotInherited))
                return false;

            return true;
        }

        #endregion
    }
}
